package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.zzyl.nursing.service.WechatService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    public static final String URL_OPENID="https://api.weixin.qq.com/sns/jscode2session";
    public static final String ACCESS_TOKEN="https://api.weixin.qq.com/cgi-bin/token";
    public static final String PHONE_NUM="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;

    /***
     * 获取app id 和密钥id*/
    @NotNull
    private   Map<String, Object> getStringObjectHashMap() {
        // ⚠️ 安全警示：密钥必须从配置中心获取，禁止硬编码
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("appid",appId);
        dataMap.put("secret",appSecret);
        return dataMap;
    }

//    获取OpenId
    @Override
    public String getOpenId(String code) {
        Map<String, Object> dataMap = getStringObjectHashMap();
        dataMap.put("js_code",code);
        dataMap.put("grant_type","authorization_code");
        String result = HttpUtil.get(URL_OPENID, dataMap);
        JSONObject jsonObject = JSONUtil.toBean(result, JSONObject.class);
        String openid = jsonObject.getStr("openid");
        if (openid == null){
            throw new RuntimeException("报错：获取openid失败");
        }
        return openid;
    }


    @Override
    public String getPhone(String code) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", code);
        HttpResponse response = HttpUtil.createPost(PHONE_NUM + getAccessToken())
                .body(JSONUtil.toJsonStr(dataMap), "application/json")
                .execute();
        String body = response.body();
        JSONObject jsonObject = JSONUtil.toBean(body, JSONObject.class);
        String phoneNumber = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        if (phoneNumber == null){
            throw new RuntimeException("获取手机号失败");
        }
        return phoneNumber;
    }

    /***
     * 获取access token*/
    public String getAccessToken(){
        Map<String, Object> dataMap = getStringObjectHashMap();
        dataMap.put("grant_type","client_credential");
        String string = HttpUtil.get(ACCESS_TOKEN, dataMap);
        JSONObject jsonObject = JSONUtil.toBean(string, JSONObject.class);
        String accessToken = jsonObject.getStr("access_token");
        if (accessToken == null){
            throw new RuntimeException("获取access_token失败");
        }
        return accessToken;
    }
}
